package com.itzdm.message.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itzdm.client.client.WsClient;
import com.itzdm.common.context.UserContext;
import com.itzdm.common.result.PageResult;
import com.itzdm.common.result.Result;
import com.itzdm.message.domain.dto.MessageSendDto;
import com.itzdm.message.domain.po.Message;
import com.itzdm.message.service.IMessageService;
import com.itzdm.ws.config.WebSocketSingleServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @作者：张德明
 * @时间：2025/4/5 15:37
 */
@Api(tags = "消息相关接口")
@RestController
@RequiredArgsConstructor
@Slf4j
public class MessageController {

    private final IMessageService messageService;

    private final WsClient wsClient;


    /**
     * 获取与指定用户的聊天记录
     *
     * @param friendId 好友ID
     * @param page     页码
     * @param size     每页条数
     * @return 聊天记录列表
     */
    @GetMapping("/chat/{friendId}")
    @ApiOperation("获取与指定用户的聊天记录")
    public Result<PageResult> getChatMessages(
            @PathVariable Long friendId,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "20") Integer size) {

        // 获取当前登录用户ID
        Long userId = UserContext.getUser();
        log.info("获取与用户{}的聊天记录, 当前用户: {}", friendId, userId);

        // 分页参数
        Page<Message> messagePage = new Page<>(page, size);

        // 使用自定义查询方法，根据用户消息关联表获取消息
        // 构建分页结果
        PageResult pageResult = messageService.getChatMessagesByUserRelation(messagePage, userId, friendId);
        return Result.success(pageResult);
    }

    /**
     * 发送消息
     *
     * @param messageSendDto 消息对象
     * @return 操作结果
     */
    @PostMapping("/sendMsg")
    @ApiOperation("发送消息")
    public Result<Message> sendMessage(@RequestBody MessageSendDto messageSendDto) {
        Long userId = UserContext.getUser();
        log.info("发送消息: {},", messageSendDto);
        // 保存消息
        Message message = messageService.sendMessage(messageSendDto, userId);
        // 通过WebSocket发送消息
        com.itzdm.client.domain.po.Message messagePo = new com.itzdm.client.domain.po.Message();
        BeanUtils.copyProperties(message, messagePo);
//        WebSocketSingleServer.sendMessage(messagePo.getReceiverUserId(), messagePo);
        wsClient.sendMsg(messagePo.getReceiverUserId(), messagePo);
        return Result.success(message);
    }

    /**
     * 获取未读消息数
     * <p>
     * 返回：
     * - totalUnread: 总未读消息数
     * - unreadBySender: 按发送者分组的未读消息数，格式为 {发送者ID: 未读数量}
     * - recentUnread: 最近的5条未读消息
     *
     * @return 未读消息数据
     */
    @GetMapping("/unread/count")
    @ApiOperation("获取未读消息数")
    public Result<Map<String, Object>> getUnreadMessageCount() {
        // 获取当前登录用户ID
        Long userId = UserContext.getUser();
        log.info("获取未读消息数, 用户: {}", userId);
        // 查询每个好友的未读消息数
        Map<String, Object> result = messageService.getUnreadMessageCount(userId);
        return Result.success(result);
    }

    /**
     * 将消息标记为已读
     *
     * @param friendId 好友ID
     * @return 操作结果
     */
    @PutMapping("/read/{friendId}")
    @ApiOperation("将与指定用户的消息标记为已读")
    public Result<Void> markMessagesAsRead(@PathVariable Long friendId) {
        // 获取当前登录用户ID
        Long userId = UserContext.getUser();
        log.info("将与用户{}的消息标记为已读, 当前用户: {}", friendId, userId);
        messageService.markMessagesAsRead(userId, friendId);
        // 通过webSocket通知对方
        String message = "READ_ACK";
        wsClient.sendMessage(friendId, message);
        return Result.success();
    }


    @DeleteMapping("/delete")
    @ApiOperation("删除双方的聊天记录")
    public Result<Void> deleteMessage(@RequestParam("friendId") Long friendId) {
        Long userId = UserContext.getUser();
        log.info("删除1方的聊天记录, userId: {}, friendId: {}", userId, friendId);
        messageService.deleteMessage(userId, friendId);
        return Result.success();
    }
}
